<template>
  <div>
    <el-row>
      <el-col :span="12">
        <video ref="videoElement" class="video" autoplay />
        <div>
          <el-button class="button" @click="toggleCamera">
            {{ cameraActive ? '关闭摄像头' : '打开摄像头' }}
          </el-button>
          <span v-if="customerId">
            <el-button class="button" @click="takeSnapshot">采图</el-button>
            <el-button class="button" @click="toggleRecording">
              {{ recording ? '停止录制' : '开始录制' }}
            </el-button>
            <el-button class="button" @click="captureVideo">视频采图</el-button>
          </span>
          <span style="float: right">已选择{{ checkedImage.length }}张</span>
        </div>
      </el-col>
      <el-col
        :span="12"
        style="height: 410px; overflow-x: hidden; overflow-y: scroll"
      >
        <div
          style="
            overflow-y: scroll;
            overflow-x: hidden;
            height: 410px;
            width: 1616px;
            display: ruby;
          "
        >
          <el-checkbox-group v-model="checkedImage" @change="checkedImageSet">
            <el-checkbox
              v-for="(fit, index) in snapshotUrl"
              :key="index"
              :label="fit"
            >
              <el-image
                style="width: 200px; height: 200px"
                :src="fit"
                :fit="fit"
              />
            </el-checkbox>
          </el-checkbox-group>
          <div v-for="(fit, index) in snapshotUrl" :key="index">
            <!-- <span class="demonstration">{{ fit }}</span> -->

            <!-- <el-image style="width: 200px; height: 200px" :src="fit" :fit="fit" /> -->
          </div>
        </div>
      </el-col>

      <el-col :span="24">
        <hr />
      </el-col>
      <el-col :span="24">
        <div
          style="
            overflow-y: scroll;
            overflow-x: hidden;
            height: 410px;
            width: 1616px;
            display: ruby;
          "
        >
          <div
            v-for="(fit, index) in recordedVideoUrl"
            :key="index"
            style="margin-left: 10px"
            @click="selectVideo(index)"
          >
            <video
              ref="videoElements"
              v-if="recordedVideoUrl"
              :src="fit"
              autoplay
              controls
              style="width: 200px; height: 200px"
              @loadedmetadata="onLoadedMetadata(index)"
            />
          </div>
          <!-- @pause="onPause(index)"@play="onPlay(index)" -->
        </div>
      </el-col>
    </el-row>
    <div style="display: flex">
      <canvas ref="canvasElement" style="display: none" />
      <!-- 隐藏的 Canvas 用于绘制截图 -->
      <canvas ref="canvasElementa" style="display: none"></canvas>
      <!-- <el-button class="button" @click="downloadImage">下载图片</el-button>
    <el-button class="button" @click="downloadVideo">下载视频</el-button> -->

      <!-- <div style="">
      <img :src="snapshotUrl" v-if="snapshotUrl" alt="截图预览" />
    </div> -->
    </div>
  </div>
</template>
<script>
export default {
  props: {
    imageList: {
      default: [],
      type: Array,
    },
    videoList: {
      default: [],
      type: Array,
    },
    customerId: {
      default: '',
      type: String,
    },
  },
  data() {
    return {
      selectedVideoIndex: -1, // 当前选中的视频索引
      screenshotBase64: null, // 截图结果
      checkedImage: [],
      cameraActive: false,
      recording: false,
      snapshotUrl: [],
      recordedVideoUrl: [],
      stream: null,
      videoElement: null,
      canvasElement: null,
      mediaRecorder: null,
      chunks: [],

      rotate: {
        x: 0,
        y: 0,
      },
    };
  },
  watch: {
    imageList(newVal, oldVal) {
      this.snapshotUrl = newVal;
    },
    videoList(newVal, oldVal) {
      this.recordedVideoUrl = newVal;
    },
  },
  mounted() {
    this.videoElement = this.$refs.videoElement;
    this.canvasElement = this.$refs.canvasElement;
  },
  created() {
    // this.toggleCamera();
  },
  methods: {
    // 选择视频
    selectVideo(index) {
      this.selectedVideoIndex = index;
    },
    // 截取当前选中视频的截图
    async captureVideo(index) {
      // if (this.selectedVideoIndex !== index) return;

      const video = this.$refs.videoElements[this.selectedVideoIndex];
      if (!video || video.paused) return;

      // 创建临时 Canvas
      const canvas = document.createElement('canvas');
      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;
      const ctx = canvas.getContext('2d');
      ctx.drawImage(video, 0, 0, canvas.width, canvas.height);

      // 转换为 Base64
      this.snapshotUrl.push(canvas.toDataURL('image/png'));
    },
    // 视频元数据加载完成
    onLoadedMetadata(index) {
      // 初始化视频尺寸等
    },
    toggleCamera() {
      if (!this.cameraActive) {
        navigator.mediaDevices
          .getUserMedia({ video: true })
          .then((stream) => {
            this.stream = stream;
            this.videoElement.srcObject = stream;
            this.cameraActive = true;
          })
          .catch((error) => {
            console.error('无法打开摄像头:', error);
          });
      } else {
        this.videoElement.srcObject = null;
        this.stream.getTracks().forEach((track) => {
          track.stop();
        });
        this.cameraActive = false;
      }
    },
    takeSnapshot() {
      const context = this.canvasElement.getContext('2d');
      context.drawImage(
        this.videoElement,
        0,
        0,
        this.canvasElement.width,
        this.canvasElement.height
      );
      this.snapshotUrl.push(this.canvasElement.toDataURL());
      this.$emit('image', this.snapshotUrl);
    },
    checkedImageSet() {
      this.$emit('checkedImageSet', this.checkedImage);
    },
    toggleRecording() {
      if (!this.recording) {
        this.startRecording();
      } else {
        this.stopRecording();
      }
    },
    startRecording() {
      if (MediaRecorder.isTypeSupported('video/webm')) {
        this.chunks = [];
        this.mediaRecorder = new MediaRecorder(this.stream, {
          mimeType: 'video/webm',
        });
        this.mediaRecorder.ondataavailable = (e) => {
          if (e.data && e.data.size > 0) {
            this.chunks.push(e.data);
          }
        };
        this.mediaRecorder.onstop = () => {
          const recordedBlob = new Blob(this.chunks, { type: 'video/webm' });
          this.chunks = [];
          // this.recordedVideoUrl.push(URL.createObjectURL(recordedBlob));

          // 1. 获取Blob对象
          fetch(URL.createObjectURL(recordedBlob))
            .then((response) => response.blob()) // 将Blob URL转换为Blob对象
            .then((blob) => {
              // 2. 使用FileReader读取Blob内容为Base64
              const reader = new FileReader();
              reader.onloadend = () => {
                const base64String = reader.result; // Base64字符串

                // 如果只需要Base64数据部分（去掉前缀），可以这样处理：
                const base64Data = base64String.split(',')[1];
                this.recordedVideoUrl.push(base64String);
                this.$emit('video', this.recordedVideoUrl);
              };
              reader.readAsDataURL(blob); // 读取为Data URL（Base64格式）
            })
            .catch((error) => {
              console.error('Error converting Blob to Base64:', error);
            });
        };
        this.mediaRecorder.start();
        this.recording = true;
      } else {
        console.error('不支持录制视频');
      }
    },
    stopRecording() {
      if (this.recording) {
        this.mediaRecorder.stop();
        this.mediaRecorder = null;
        this.recording = false;
      }
    },
    downloadImage() {
      if (this.snapshotUrl) {
        const a = document.createElement('a');
        a.href = this.snapshotUrl;
        a.download = 'snapshot.png';
        a.click();
      }
    },
    downloadVideo() {
      if (this.recordedVideoUrl) {
        const a = document.createElement('a');
        a.href = this.recordedVideoUrl;
        a.download = 'recorded_video.webm';
        a.click();
      }
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-checkbox {
  margin-right: 5px;
}
</style>
